package com.freeter.modules.gen.utils;

import com.freeter.common.utils.SpringContextUtils;
import com.freeter.modules.gen.entity.TableEntity;
import com.freeter.modules.gen.service.MysqlDataBaseService;
import com.freeter.modules.gen.service.OracleDataBaseService;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Jerry Li
 */
@Component
public class DocMapFactory {
    public static final String TABLE_INFOS = "tableInfos";
    public static final String DATABASE_NAME = "databaseName";
    public static final String ORACLE = "Oracle";
    public static final String MY_SQL = "MySQL";
    public static final String MYSQL_DATA_BASE_SERVICE = "mysqlDataBaseService";
    public static final String ORACLE_DATA_BASE_SERVICE = "oracleDataBaseService";


    public static Map<String, Object> build() throws SQLException {
        Map<String, Object> map = new HashMap<>(2);
        String databaseProductName = getDatabaseProductName();
        if (MY_SQL.equals(databaseProductName)) {

            MysqlDataBaseService mysqlDataBaseService = (MysqlDataBaseService) SpringContextUtils
                    .getBean(MYSQL_DATA_BASE_SERVICE);
            String databaseName = mysqlDataBaseService.queryDatabaseName();
            List<TableEntity> tableList = mysqlDataBaseService.getTableList();

            map.put(TABLE_INFOS, tableList);
            map.put(DATABASE_NAME, databaseName);

        } else if (ORACLE.equals(databaseProductName)) {

            OracleDataBaseService oracleDataBaseService = (OracleDataBaseService) SpringContextUtils
                    .getBean(ORACLE_DATA_BASE_SERVICE);
            String databaseName = oracleDataBaseService.queryDatabaseName();
            List<TableEntity> tableList = oracleDataBaseService.getTableList();

            map.put(TABLE_INFOS, tableList);
            map.put(DATABASE_NAME, databaseName);

        }

        return map;
    }

	public static String getDatabaseProductName() throws SQLException {

		DataSource dataSource = (DataSource) SpringContextUtils.getBean("dataSource");
		Connection connection = dataSource.getConnection();
		System.out.println(connection.isClosed());
		String databaseProductName = connection.getMetaData().getDatabaseProductName();
		connection.close();

		return databaseProductName;
	}

    public static Boolean isMysql() throws Exception {
		return MY_SQL.equals(DocMapFactory.getDatabaseProductName());
	}
}
